package org.anderground.editor.gui.toolbar;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JToolBar;

import org.anderground.core.model.Line;
import org.anderground.editor.gui.MainWindow;
import org.anderground.editor.gui.view.standard.ViewTriggers;
import org.anderground.editor.model.EditorModel;

@SuppressWarnings("serial")
public class LineToolBar extends JToolBar {
	public LineToolBar(MainWindow parent) {
		LineBox lineBox = new LineBox();
		add(new LineColorPreview(lineBox));
		add(lineBox);
		// add(new AddLineButton(parent));
	}

	class LineBox extends JComboBox implements Observer {
		LineBox() {
			EditorModel.getInstance().addObserver(this);
			setFocusable(false);
			addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					Line line = (Line) LineBox.this.getSelectedItem();
					ViewTriggers.addTunelsLine = line == null ? new Line()
							: line;
				}

			});

		}

		@Override
		public void update(Observable o, Object arg) {
			Line selected = (Line) this.getSelectedItem();

			this.removeAllItems();
			for (Line line : EditorModel.getInstance().getData().getLines()) {
				this.addItem(line);
				if (line == selected) {
					this.setSelectedItem(selected);
				}
			}

		}

	}

	// class AddLineButton extends JButton {
	// AddLineButton(final MainWindow parent) {
	// super("Add line");
	// addActionListener(new ActionListener() {
	// @Override
	// public void actionPerformed(ActionEvent e) {
	// Line line = new Line();
	// EditsManager.getInstance().performAction(new AddLineAction(line));
	// Logger.i("new line added");
	// }
	//
	// });
	//
	// }
	// }

	class LineColorPreview extends JPanel {
		private Color color = Color.WHITE;

		LineColorPreview(final LineBox lineBox) {
			this.setPreferredSize(new Dimension(20, 16));
			this.setMaximumSize(new Dimension(10, 22));
			this.setMinimumSize(new Dimension(10, 10));
			lineBox.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					if (lineBox.getSelectedItem() == null)
						return;
					color = new Color(((Line) lineBox.getSelectedItem())
							.getColor());
					repaint();
				}

			});
		}

		@Override
		public void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.setColor(color);
			g.fillRect(0, 2, this.getWidth() - 3, getHeight() - 5);

		}
	}

}
